<?php
/**
 * Created by Chongyi
 * Date: 2015/10/5 0005
 * Time: 上午 9:08
 */

namespace App\B2BProject\Admin\Authority;

use App\B2BProject\Admin\Administrator;
use App\B2BProject\Admin\AdministratorInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * Class Auth
 *
 * 后台授权认证模块
 *
 * @package App\B2BProject\Admin\Authority
 */
class Auth
{
    const ADMIN_LOGIN_SESSION_FLAG = 'login-admin';
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var SessionInterface
     */
    protected $session;

    /**
     * @var bool
     */
    protected $logout = false;

    /**
     * @var Administrator
     */
    protected $user;

    /**
     * @param Request|null $request
     */
    public function __construct(Request $request = null)
    {
        $this->request = $request ?: Request::createFromGlobals();
    }

    /**
     * 设置 Session 管理器
     *
     * @param SessionInterface $session
     */
    public function setSessionStore(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * 根据凭据验证或登录
     *
     * @param array     $credentials
     * @param bool|true $login
     *
     * @return bool
     */
    public function attempt(array $credentials, $login = true)
    {
        if (!isset($credentials['user'])) {
            return false;
        }

        try {
            $user = Administrator::where('user', '=', $credentials['user'])->firstOrFail();
        } catch (ModelNotFoundException $e) {
            return false;
        }

        if (\Hash::check($credentials['password'], $user->password)) {
            if ($login) {
                $this->login($user);
            }

            return true;
        }

        return false;
    }

    /**
     * 仅验证凭据
     *
     * @param array $credentials
     *
     * @return bool
     */
    public function validate(array $credentials)
    {
        return $this->attempt($credentials, false);
    }

    /**
     * 检查登录状态
     *
     * @return bool
     */
    public function check()
    {
        return ! is_null($this->user());
    }

    /**
     * 检查是否为访客
     *
     * @return bool
     */
    public function guest()
    {
        return !$this->check();
    }

    /**
     * 获取当前登录用户
     *
     * @return Administrator|null
     */
    public function user()
    {
        if ($this->logout) {
            return null;
        }

        if (!is_null($this->user)) {
            return $this->user;
        }

        $id = $this->session->get(self::ADMIN_LOGIN_SESSION_FLAG);

        $user = null;

        if (!is_null($id)) {
            $user = Administrator::find($id);
        }

        return $this->user = $user;
    }

    /**
     * 登录指定用户
     *
     * @param AdministratorInterface $admin
     */
    public function login(AdministratorInterface $admin)
    {
        $this->updateSession($admin->id);

        $admin->increment('login_count');

        $admin->last_login = date('Y-m-d H:i:s', time());
       /* $admin->last_login_ip = \Request::getClientIp();*/
        $admin->last_login_ip = $_SERVER['REMOTE_ADDR'];
        $admin->save();

        $this->user = $admin;

        $this->logout = false;
    }

    /**
     * 登出（注销）
     */
    public function logout()
    {
        $this->user = null;

        $this->logout = true;

        $this->session->remove(self::ADMIN_LOGIN_SESSION_FLAG);
    }

    /**
     * 更新 Session 状态
     *
     * @param $id
     */
    public function updateSession($id)
    {
        $this->session->remove(self::ADMIN_LOGIN_SESSION_FLAG);

        $this->session->set(self::ADMIN_LOGIN_SESSION_FLAG, $id);
    }


}